import 'package:get/get.dart';
import 'package:vischat/core/utils/jverify.dart';
import 'package:vischat/core/utils/tencent/tencent_init.dart';
import 'package:vischat/data/datasources/local/secure_local.dart';
import 'package:vischat/data/models/user_model.dart';

class AuthService extends GetxService {
  final SecureLocal _secureLocal = Get.find();

  final _loginState = LoginState.notLoggedIn.obs;
  final _userInfo = Rx<UserModel?>(null);
  final _canOneClickLogin = false.obs;

  get loginState => _loginState.value;
  get userInfo => _userInfo.value;
  get canOneClickLogin => _canOneClickLogin.value;

  final unread = 0.obs;

  @override
  void onInit() {
    super.onInit();
    preLogin();
    fetchUser(init: true);
  }

  Future<void> preLogin() async {
    bool res = await JverifyUtil.isInitSuccess();
    if(res) {
      _canOneClickLogin.value = await JverifyUtil.preLogin();
    }
  }

  UserModel? fetchUser({bool init = false}) {
    if (init) {
      UserModel? user = _secureLocal.getUser();
      if (user != null && user.userId != null) {
        _loginState.value = LoginState.loggedIn;
        _userInfo.value = user;
      }
    }
    return _userInfo.value;
  }

  Future<void> setLoggedIn(UserModel userInfo, String token) async {
    _userInfo.value = userInfo;
    _loginState.value = LoginState.loggedIn;
    await _secureLocal.saveToken(token);
    await _secureLocal.saveUser(userInfo);
    await TencentInit.loginIM();
  }

  Future<void> setNotLoggedIn() async {
    _loginState.value = LoginState.notLoggedIn;
    await _secureLocal.deleteToken();
  }
}

enum LoginState { loggedIn, notLoggedIn }
